亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 javascript 繪制帶有背景圖像的畫布文本

使用 javascript 繪制帶有背景圖像的畫布文本

aluckdog 2023-07-06 15:19:45
我在繪制畫布時需要實現這一點:首先我用畫布繪制圖像作為背景然后用另一張圖像的顏色繪制文本=> 問題是 bg-image 與 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>測試鏈接: http: //jsfiddle.net/1x5dfgty/14/
查看完整描述

1 回答

?
翻閱古今

TA貢獻1780條經驗 獲得超5個贊

在“destination-over”模式下使用globalCompositeOperation允許您在畫布上繪制背景:

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>



查看完整回答
反對 回復 2023-07-06
  • 1 回答
  • 0 關注
  • 195 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號