How to make a copy of a sprite on an HTML5 canvas?

流过昼夜 提交于 2019-12-25 19:03:13

问题


I'm trying to make a 2-D platformer-style game using javascript and an HTML5 canvas. While working on the random level generation I stumbled into a problem. I have the sprites working fine, but when I try to load the next platform the old one disappears. I figured that this problem would be solved if I copied the image, but I don't know how. I tried searching it up on google but most sites I went to weren't very understandable or were related to a different problem. Can you please help out?


回答1:


It is easy way to copy an image:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 50, 50);

function copy() {
    var imgData = ctx.getImageData(10, 10, 50, 50); 
    for (var i = 0; i < imgData.data.length; i += 4) {
        imgData.data[i] = 255 - imgData.data[i];
        imgData.data[i+1] = 255 - imgData.data[i+1];
        imgData.data[i+2] = 255 - imgData.data[i+2];
        imgData.data[i+3] = 255;
    }
    ctx.putImageData(imgData, 10, 70);
}

</script>

<button onclick="copy()">Copy</button>

</body>
</html>
Also, for correct work 'getImageData' with images I should been start my page from localhost. If path like 'D:/.../myPage.html' this method didn't work.

来源:https://stackoverflow.com/questions/32386863/how-to-make-a-copy-of-a-sprite-on-an-html5-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!