我怎样才能生产一种牙膏" HTML5 Canvas中的样式线?

时间:2014-12-16 04:11:18

标签: canvas html5-canvas stroke

手头的任务之一是在绘图时创建几乎3d效果。它给人的印象是笔划来自管道:

A tube stroke

如何使用Canvas创建此效果?

为了给出一些背景,而不是使用Canvas绘图,我会使用圆形"画笔"纹理,然后在动态纹理上插入圆圈。这给了我相同的效果,但在移动设备上却非常缓慢。

2 个答案:

答案 0 :(得分:2)

您可以使用阴影创建3D效果:

你需要绘制2条线,第2条线有阴影。

  • 用圆形线条画一条粗白线

  • 用阴影画第二行。让它的阴影出现在第一行的底部。

enter image description here

这里的“技巧”是只显示第二行的阴影(第二行本身不会出现)。这是通过在画布上方绘制第二行并使用shadowOffsetY将第二行的阴影推到第一行底部的画布上来完成的。

虽然遮蔽是一项相当昂贵的操作,但它比建立一系列形成牙膏的图像便宜得多。

// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// floodfill the canvas with purple
ctx.fillStyle='#9933cc';
ctx.fillRect(0,0,cw,ch);

// draw a wide white line with round linecap
ctx.beginPath();
ctx.moveTo(50,50);
ctx.lineTo(150,75);
ctx.lineTo(250,125);
ctx.lineWidth=25;
ctx.lineCap='round';
ctx.strokeStyle='white';
ctx.stroke();

// set shadowing to black with 10px blur size
ctx.shadowColor='black'
ctx.shadowBlur=10;

// draw the shadow way below the line
ctx.shadowOffsetY=212.5;

// Draw a line up off the top of the canvas
// The line will not be visible
// But the line's shadow will be visible
//     over the bottom of the wide white line
ctx.beginPath();
ctx.moveTo(42,50-200);
ctx.lineTo(150,75-200);
ctx.lineTo(258,127-200);
ctx.lineWidth=10;
ctx.strokeStyle='red';
ctx.stroke();
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

答案 1 :(得分:1)

您仍然希望使用圆形画笔纹理。

var texture = new Image;
texture.src = 'brush.png'

然后您需要创建画布并将其添加到您的页面某处,例如:

var canvas = document.createElement('canvas');
canvas.context = canvas.getContext('2d');
canvas.width = 200;
canvas.height = 300;
document.getElementByID('parentDiv').appendChild(canvas)

然后你需要一个像这样的事件监听器来将它绘制到画布上。

function moveMouse(xx,yy){
     canvas.context.drawImage(texture, xx, yy)
}

canvas.addEventListener('mousemove', function(e){
    if(e.clientX){
        var rect = this.getBoundingClientRect();
        if(rect)            moveMouse(e.clientX - rect.left, e.clientY - rect.top)
        else                moveMouse(e.clientX  - this.offsetLeft, e.clientY - this.offsetTop);
    }else if(e.offsetX)     moveMouse(e.offsetX, e.offsetY);
    else if(e.layerX)       moveMouse(e.layerX, e.layerY);
    else console.warn("Couldn't Determine Mouse Coordinates");
})

祝你好运!