2016-10-22 65 views
1

在这里,我试图绘制具有相同不透明度,并排的方格。javascript画布绘制的形状看起来像它们重叠,即使x和y说他们并排

即使每个方格的x位置恰好是一个正方形的宽度,但它们看起来好像在其上绘制了更多的半透明正方形。第一个正方形具有较高的不透明度,最后一个正方形的正方形效果更好。

Result

我有控制台注销正在呈现平方数,它是如预期。所以我不相信有多余的正方形被渲染在它们之上。 我也检查过x位置以查看是否有重叠,哪些没有重叠。那么可能会导致广场有不同的透明度?

const windowWidth = window.innerWidth; 
const windowHeight = window.innerHeight; 
const canvas = document.getElementById("app-canvas"); 
canvas.width = windowWidth; 
canvas.height = windowHeight; 
canvas.style.position = "absolute"; 
canvas.style.backgroundColor = "grey"; 
canvas.style.zIndex = 1; 
document.body.appendChild(canvas); 

class Scene { 
    constructor() { 
     this.orbs = []; 
     this.squares = []; 
     this.context = canvas.getContext("2d"); 
    } 

    addOrb(orb) { 
     this.orbs.push(orb); 
    } 

    addSquare(square) { 
     this.squares.push(square); 
    } 

    render() { 
     this.context.clearRect(0, 0, windowWidth, windowHeight); 
      this.squares.forEach(square => { 
       square.draw(this.context); 
      }); 

    } 
} 

class Square { 
    constructor(options) { 
     this.options = options; 
    } 

    draw(ctx) { 
     let x = this.options.x; 
     let y = this.options.y; 
     let width = this.options.width; 
     let height = this.options.height; 
     ctx.moveTo(x,y); 
     ctx.rect(x, y, width, height); 
     ctx.fillStyle = "rgba(255,255,255,.1)"; 
     ctx.fill(); 
    } 
}; 

let squares = []; 
let squareWidth = 200; 
let squareHeight = 200; 

let x = 0; 
let y = 0; 
for (let i = 0; i < windowWidth; i+=squareWidth) { 
    x += squareWidth; 
    let square = new Square({ 
     x, y: 0, width: squareWidth, height: squareHeight 
    }); 
    console.log(square) 
    squares.push(square); 
} 
console.log(squares.length); 

let scene = new Scene(); 
squares.forEach(square => scene.addSquare(square)); 

scene.render(); 

回答

2

您需要在每个矩形之前致电ctx.beginPath()。否则,.rect()的呼叫只是添加到路径中,fill()填充整个事情。

draw(ctx) { 
    let x = this.options.x; 
    let y = this.options.y; 
    let width = this.options.width; 
    let height = this.options.height; 
    ctx.beginPath(); // <========= this 
    ctx.moveTo(x,y); 
    ctx.rect(x, y, width, height); 
    ctx.fillStyle = "rgba(255,255,255,.1)"; 
    ctx.fill(); 
} 

你也可以考虑只使用.fillRect()

相关问题