• 赚钱入口【需求资源】限时招募流量主、渠道主,站长合作;【合作模式】CPS长期分成,一次推广永久有收益。主动打款,不扣量;

Javascript绘制文本与背景时遮挡的问题

JavaScript cps12345 3周前 (11-04) 20次浏览 0个评论

在绘制画布时,我需要实现以下目标:

  • 首先,我用画布绘制图像作为背景
  • 然后用其他图像的颜色绘制文本

=>问题是bg图像已被text-img覆盖

window.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    var img1 = document.getElementById("bg-img");    
    var img2 = document.getElementById("text-img");

    // draw the first image as background
    ctx.drawImage(img1, 0, 0);

    // put text on canvas
    ctx.save();
    ctx.beginPath();   
    ctx.font = "50pt Verdana";
    ctx.fillText("XBOX", 10, 100);
    ctx.fill();
    // use compositing to draw the background image
    // only where the text has been drawn
    ctx.beginPath();
    ctx.globalCompositeOperation = "source-atop";
    ctx.drawImage(img2, 0, 0, img2.width, img2.height, 0, 0, canvas.width, canvas.height);
    ctx.restore();
    
};
<p>Image to use:</p>

<img id="bg-img" src="http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg" alt="">
<img id="text-img" src="http://www.html5canvastutorials.com/demos/assets/yoda.jpg" alt="">

<p>Canvas:</p>

<canvas id="myCanvas" width="220" height="297"
style="border:1px solid #d3d3d3;">
</canvas>

解决

globalCompositeOperation的值设置为”destination-over”

function onReady() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    var img1 = document.getElementById("bg-img");
    var img2 = document.getElementById("text-img");
    // draw the first image as background
    // uncomment this to see the problem
    ctx.save();
    ctx.beginPath();
    // put text on canvas
    ctx.font = "50pt Verdana";
    ctx.fillText("XBOX", 10, 100);
    ctx.fill();
    // use compositing to draw the background image
    // only where the text has been drawn
    ctx.closePath();
    ctx.globalCompositeOperation = "source-atop";
    ctx.drawImage(img2, 0, 0, img2.width, img2.height, 0, 0, canvas.width, canvas.height);
    ctx.restore();
    ctx.globalCompositeOperation = 'destination-over';
    ctx.drawImage(img1, 0, 0);
    //ctx.drawImage(img1, 0, 0, img1.width, img1.height, 0, 0, canvas.width, canvas.height); // Stretch to fit image
}
window.addEventListener("load", onReady);
<p>Image to use:</p>

<img id="bg-img" src="http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg" alt="">
<img id="text-img" src="http://www.html5canvastutorials.com/demos/assets/yoda.jpg" alt="">

<p>Canvas:</p>

<canvas id="myCanvas" width="220" height="297"
style="border:1px solid #d3d3d3;">
</canvas>
喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址