问题
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>
来源:https://stackoverflow.com/questions/32386863/how-to-make-a-copy-of-a-sprite-on-an-html5-canvas