开发者

recursive image manipulation (Canvas, HTML5, Javascript)

I’m trying to use Canvas for a fractal algorithm that requires one to draw something, then capture that image, draw some mangled copies of it, then capture that image, etc. I’m running into a problem, though, because toDataURL() seems to be causing a failure in either the clear screen command ("clearRect") or the restore transformation matrix command ("restore").

The code below is intended to draw a black square, then copy the canvas to a variable named “img”, translate down and to the right, then paste “img” to the new position. The result should be two squares. But instead it’s first 1 square, then 2 squares, then 3, then 4 … (Then it goes out of bounds, but presumably it’s still copying squares off the page.)

Any help will be greatly, greatly appreciated.

Here's a link to the code in action: https://www.msu.edu/~brown202/dataURLproblem.html

Here's the code:

    <html>
        <head>
            <script type="application/x-javascript">
                function draw() {
                    var canvas = document.getElementById("fractal");
                    if (canvas.getContext) {
                        var ctx = canvas.getContext("2d");
                        var img;
                        ctx.clearRect(0,0,400,400);    // clear the canvas, which measures 400 by 400
                        ctx.fillRect (0,0,100,100);    // draw a square
                        ctx.save();
                            img = canvas.toDataURL();    // store the canvas image in "img"
                            ctx.translate(100,100);      // shift picture
                            ctx.drawImage(img, 0,0);    // draw the stored image of the canvas in the new place
                        ctx.restore();
                    }
                }
                function init() {
                    setInterval(draw,500);          // repeat every 500 ms.
                }
            </script>
        </head>
        <body onload="init();">
            <canvas id="fractal" width="400" height="400">
                <p>This animation requires a browser that supports the
                <a href="http://www.w3.org/html/wg/html5/">HTML5</a> 
                &lt;canvas&gt; 开发者_如何学编程feature.</p>
            </canvas>
        </body>
    </html>


If you look at the javascript console when your page runs, it's generating errors:

Uncaught TypeError: Type error

This is because you're trying to pass a string (the dataURL version of the image) to drawImage when the drawImage function is expecting an image/canvas.

The drawImage function can take in a canvas element as its argument, which will do what you want.

Instead of doing:

img = canvas.toDataURL();
ctx.drawImage(img, 0,0);

Just do:

ctx.drawImage(canvas, 0,0);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜