如何使用HTML5 Canvas和JavaScript将绘制的对象显示在图像上?

时间:2012-10-18 08:27:35

标签: html5 canvas

我想知道是否有人可以帮我弄清楚如何使用HTML5 Canvas和JavaScript在图像上绘制对象?

我已经写了一个示例来展示我的问题(只要你有一个名为choc.jpg的图像可用它应该有效)。我希望香蕉对象出现在JPEG上,但事实并非如此。我是HTML5和画布的新手,非常感谢被指向正确的方向。 非常感谢你的帮助!

<!DOCTYPE HTML>
<script>

window.onload=function() {
var testcanvas=document.getElementById("bananaDesign");
var testcontext=testcanvas.getContext('2d');

//set a background image
/* if I comment out this section no image appears and the banana gets drawn. How do I get banana to go over image? */

var importedImg = new Image();
importedImg.src = 'pictures/choc.JPG';
importedImg.onload = function(){
testcontext.drawImage(importedImg, 10, 10);
};


//draw a banana
testcontext.fillStyle = "#FFA824";
testcontext.beginPath();
testcontext.moveTo(62,20);
testcontext.lineTo(80,20); //2
testcontext.lineTo(80,30); //3
testcontext.lineTo(90,50); //4
testcontext.lineTo(80,85); //5
testcontext.lineTo(45,95); //6
testcontext.lineTo(40,80); //7
testcontext.lineTo(60,60); //8
testcontext.lineTo(60,30); //9
testcontext.fill();
}

</script>


<canvas id="bananaDesign" width="500" height="600" style="border: 5px red solid">
<p>Your browser does not display HTML5 canvas. Please update to view this design.</p>
</canvas>

2 个答案:

答案 0 :(得分:1)

图像以异步方式加载,因此在您绘制香蕉(因此在其上方)之后,它实际上被绘制到画布上。在将图像绘制到画布后,快速解决方法是将香蕉绘制代码移动到图像加载处理程序中(请参阅http://jsfiddle.net/5pGqV/,回想起我选择的背景图像并不理想;)): / p>

<!DOCTYPE HTML>
<script>

    window.onload=function() {
        var testcanvas=document.getElementById("bananaDesign");
        var testcontext=testcanvas.getContext('2d');

        //set a background image
        /* if I comment out this section no image appears and the banana gets drawn. How do I get banana to go over image? */

        var importedImg = new Image();
        importedImg.src = 'pictures/choc.JPG';
        importedImg.onload = function(){

            //draw the loaded image to canvas first
            testcontext.drawImage(importedImg, 10, 10);

            //now draw a banana on top
            testcontext.fillStyle = "#FFA824";
            testcontext.beginPath();
            testcontext.moveTo(62,20);
            testcontext.lineTo(80,20); //2
            testcontext.lineTo(80,30); //3
            testcontext.lineTo(90,50); //4
            testcontext.lineTo(80,85); //5
            testcontext.lineTo(45,95); //6
            testcontext.lineTo(40,80); //7
            testcontext.lineTo(60,60); //8
            testcontext.lineTo(60,30); //9
            testcontext.fill();
        }; 
    }

</script>


<canvas id="bananaDesign" width="500" height="600" style="border: 5px red solid">
<p>Your browser does not display HTML5 canvas. Please update to view this design.</p>
</canvas>

答案 1 :(得分:1)

您需要在上下文中配置 globalCompositeOperation 属性。 在您的情况下,将值设置为'destination-over'以绘制图像。 以下是所有可能值http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-globalcompositeoperation的列表。

代码http://jsfiddle.net/gU4xc/

的示例