开发者

How do I use one canvas element as the backdrop for another canvas element?

开发者 https://www.devze.com 2023-01-21 11:16 出处:网络
I am working through the HTML5 canvas tutorial on the following website: Mozilla Developers. In this tutorial, they say that you can us开发者_运维问答e a canvas element as the backdrop of another canv

I am working through the HTML5 canvas tutorial on the following website: Mozilla Developers. In this tutorial, they say that you can us开发者_运维问答e a canvas element as the backdrop of another canvas element. I have tried to do exactly that with the following html page. Unfortunately, the debugger in chrome says failed to load resource. Am I referencing the source canvas object the correct way in the function draw2()?:

<html>
<head>
<title>CANVAS TESTING</title>
<script type="text/javascript">

function draw()
    {
    var ctx = document.getElementById('tutorial').getContext('2d');

    ctx.translate(0,document.getElementById('tutorial').height); 
    ctx.scale(1,-1)

    // Create gradients
    var lingrad = ctx.createLinearGradient(0,0,0,150);
    lingrad.addColorStop(0, '#fff');
    lingrad.addColorStop(0.5, '#66CC00');
    lingrad.addColorStop(0.5, '#fff');
    lingrad.addColorStop(1, '#00ABEB');

    var lingrad2 = ctx.createLinearGradient(0,50,0,95);
    lingrad2.addColorStop(0.25, 'rgba(0,0,0,0)');
    lingrad2.addColorStop(0.75, '#000');

    // assign gradients to fill and stroke styles
    ctx.fillStyle = lingrad;
    ctx.strokeStyle = lingrad2;

    // draw shapes
    ctx.fillRect(10,10,130,130);
    ctx.strokeRect(50,50,50,50);

    }
function draw2()
    {
    ctx=document.getElementById('canvas').getContext('2d');
    img = new Image();
    img.onload = function()
        {
        ctx.drawImage(img,0,0);
        }
    img.src = document.getElementById('tutorial');  
    }
</script>
</head>
<body onload="draw()">
<p>This is a test of canvas element.</p>
<canvas id="tutorial" width="400" height="400" style="background-color: black"></canvas>
<br /><br />
<canvas id="canvas" width="400" height="400" style="background-color: black"></canvas>
<p>
<input type="button" onclick="draw2()" value="Draw!" />
</p>
</body>


Your solution is kinda correct but you're making it waaaay more complicated than it has to be.

All you have to do is this, nothing any fancier:

var tut = document.getElementById('tutorial');
ctx.drawImage(tut,0,0); // just put in the canvas you want to draw!

Here's a live jsfiddle example if you need more detail


Ok, I just found the answer to my question.

going off the function in Draw2(), I needed to set my img.src to the following:

img.src = document.getElementById('tutorial').toDataURL();

What this does is returns the base64 encoded data string of the png image of the canvas element.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号