2014-09-12 71 views
1

我一直在试图建立我的线性渐变的各部门之间的蜱,由于某种原因,我不能让他们与梯度正确对齐,数学是很简单但它是在很大的梯度下仍然有几个像素。帆布对准线线性渐变色停止

我的HTML:

<html> 
<head> 
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
    <script type="text/javascript" src="canvas.js"></script> 
    <style type="text/css"> 
     canvas { 
      border: 1px solid black; 
     } 
    </style> 
</head> 
<body> 
    <canvas id="canvas" width="1300" height="300"></canvas> 
</body> 
</html> 

canvas.js:

$(document).ready(function() { 
    var canvas= $("canvas")[0]; 
    var canvasWidth= $("canvas").innerWidth(); 
    var canvasHeight= $("canvas").innerHeight(); 
    var ctx = canvas.getContext("2d"); 
    var size= [0, 0, canvasWidth, canvasHeight/2]; 

    var grad = ctx.createLinearGradient(size[0],size[1],size[2],0); 
    ctx.lineWidth= 2; 
    grad.addColorStop(0, 'green'); 
    grad.addColorStop(0.5, 'green'); 
    grad.addColorStop(0.5, 'yellow'); 
    grad.addColorStop(0.8, 'yellow'); 
    grad.addColorStop(0.8, 'red'); 
    grad.addColorStop(1, 'red'); 
    ctx.fillStyle = grad; 
    ctx.fillRect(size[0], size[1], size[2], size[3]); 


    ctx.translate(0, canvasHeight/2); 
    ctx.strokeStyle= "black"; 

    ctx.beginPath(); 
    ctx.moveTo(canvasWidth*0.5, -6); 
    ctx.lineTo(canvasWidth*0.5, 6); 
    ctx.stroke(); 

    ctx.beginPath(); 
    ctx.moveTo(canvasWidth*0.8, -6); 
    ctx.lineTo(canvasWidth*0.8, 6); 
    ctx.stroke(); 
}); 

的代码也是一个fiddle

正如你可以看到我创建使用createLinearGradient法3层颜色的部分,我在0.5和0.8加入止损,然后我试图在同样的空间绘制蜱。蜱向左移动几个像素,我不知道为什么。这只在大的渐变中很明显,在小渐变(如300px x 300px)中,蜱看起来处于正确的位置。

注:我不得不使用线性渐变,改变简单的彩色矩形是不是一种选择。我希望能够使用相同的代码定义渐变以及纯色部分(只需更改颜色停止)。

+0

我确认你的发现。顺便说一句,不同浏览器中不需要的偏移量是不同的。我会说不需要的偏移量取决于颜色停止中百分比与线条图中像素坐标的用户的比例。我想不出一种方法来协调差异并使梯度和线条对齐。 : -/ – markE 2014-09-13 01:21:37

+0

@markE我在Opera 12(presto engine)和firefox中测试过,它似乎没问题,看起来这是一个webkit/blnk bug – Hoffmann 2014-09-13 19:54:46

回答

0

这似乎是WebKit的特定错误。小提琴可以在Firefox,IE11和Opera 12中正确渲染(presto引擎)。我填写了一个bug report铬。