簡體   English   中英

使用圖像使用JavaScript填充畫布中的弧線

[英]Use image to fill in arc in canvas using javascript

因此,我完全不熟悉畫布,正在嘗試一個項目,在該項目中,我需要使小球以其背景作為圖像來回移動。 以下代碼是我現在正在嘗試的代碼。

ctx.beginPath();
ctx.arc(
  this.pos[0], this.pos[1], this.radius, 0, 2 * Math.PI, true
);
let tempCanvas = document.createElement("canvas"),
    tCtx = tempCanvas.getContext("2d");
let ballbackground = new Image();
if (this.color === "green") {
    ballbackground.src = "https://s26.postimg.cc/fl2vwj1mh/greenball.png";
    }
else if (this.color === "yellow") {
    ballbackground.src = "https://s26.postimg.cc/if61a18yh/yellowball.png";
    }
else if (this.color === "blue") {
    ballbackground.src = "https://s26.postimg.cc/xb4khn7ih/blueball.jpg";
    }
tempCanvas.width = 50;
tempCanvas.height = 50;
tCtx.drawImage(ballbackground,0,0,ballbackground.width, ballbackground.height,0,0,50,50);
ctx.fillStyle = ctx.createPattern(tempCanvas, "repeat");

對於移動這些球,我需要執行以下操作:

const velocityScale = timeDelta / NORMAL_FRAME_TIME_DELTA,
    offsetX = this.vel[0] * velocityScale * this.speed,
    offsetY = this.vel[1] * velocityScale * this.speed;
    this.pos = [this.pos[0] + offsetX, this.pos[1] + offsetY];

但是,問題在於,當對象移動時,它們看起來像在背景圖像上滑動,如下所示:

點擊這里查看圖片

如果我使用createPattern嘗試“不重復”,則這些球根本不會顯示。

我想要的是那些背景圖像在畫布上移動的球?

通過使用畫布變換來移動球?

 const ctx = document.querySelector("canvas").getContext("2d"); const pattern = createPattern(ctx); function drawCircleByPosition(ctx, x, y) { ctx.beginPath(); ctx.arc(x, y, 50, 0, Math.PI * 2, true); ctx.fill(); } function drawCircleByTransform(ctx, x, y) { ctx.save(); ctx.translate(x, y); ctx.beginPath(); ctx.arc(0, 0, 50, 0, Math.PI * 2, true); ctx.fill(); ctx.restore(); } function render(time) { time *= 0.001; ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.fillStyle = pattern; drawCircleByPosition(ctx, 90, 75 + Math.sin(time) * 50); drawCircleByTransform(ctx, 210, 75 + Math.sin(time) * 50); requestAnimationFrame(render); } requestAnimationFrame(render); function createPattern(ctx) { const tCtx = document.createElement("canvas").getContext("2d"); tCtx.canvas.width = 50; tCtx.canvas.height = 50; tCtx.fillStyle = "yellow"; tCtx.fillRect(0, 0, 50, 50); for (let x = 0; x < 50; x += 20) { tCtx.fillStyle = "red"; tCtx.fillRect(x, 0, 10, 50); tCtx.fillStyle = "blue"; tCtx.fillRect(0, x, 50, 10); } return ctx.createPattern(tCtx.canvas, "repeat"); } 
 canvas { border: 1px solid black; } 
 <canvas></canvas> 

請注意,除了調用saverestore您還可以只使用setTransform設置轉換,這可能會更快,因為保存和還原會保存所有狀態(fillStyle,strokeStyle,font,globalCompositeOperation,lineWidth等)。

您可以傳入自己的矩陣。

 ctx.setTransform(1, 0, 0, 1, x, y);  // for translation

和/或您可以隨時將其重置為默認值,然后使用標准的變換操作功能

 ctx.setTransform(1, 0, 0, 1, 0, 0);  // the default
 ctx.translate(x, y);

或您想做的事情的任何組合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM