HTML5 Canvas教程: 怎么画一粒胶囊

最终成品

步骤

打开你的文本编辑器,然后写一个script标签,复制下方那堆很长的代码放进这个标签.

在最底部写进以下内容:

保存为HTML文件,在Chrome或Firefox等现代浏览器中运行即可.

是不是很容易呢!

PS:由于是矢量图,等比例调整w,h,unit后不会导致失真.

代码

var img_pill = (function() { var gray = '#DEDFDE', darkgray = '#CACACA', white = '#FFF' , blue = '#1BA1E2', skyblue = '#4EBEE4', navyblue = '#2CA2E1'; var unit = 20; var w = 400, h = 200; var canvas = document.createElement('canvas'); var ctx; with(canvas) { width = w; height = h; ctx = getContext('2d'); } with(ctx) { save(); fillStyle = darkgray; fillRect(3 * unit, 0 , w - 3 * unit * 2, 1 * unit ); fillRect(3 * unit, h - 1 * unit, w - 3 * unit * 2, 1 * unit ); fillRect(2 * unit, 1 * unit , w - 2 * unit * 2, 1 * unit ); fillRect(2 * unit, h - 2 * unit, w - 2 * unit * 2, 1 * unit ); fillRect(1 * unit, 2 * unit , w - 1 * unit * 2, 1 * unit ); fillRect(1 * unit, h - 3 * unit, w - 1 * unit * 2, 1 * unit ); fillRect(0 , 3 * unit , w , h - 3 * unit * 2); restore(); for(var i = 2; i--;) { save(); fillStyle = white; if(i == 1) { translate(w, h); rotate(Math.PI / 180 * 180); fillStyle = blue; } beginPath(); moveTo(3 * unit, 1 * unit ); lineTo(w / 2 , 1 * unit ); lineTo(w / 2 , h - 1 * unit); lineTo(3 * unit, h - 1 * unit); lineTo(3 * unit, h - 2 * unit); lineTo(2 * unit, h - 2 * unit); lineTo(2 * unit, h - 3 * unit); lineTo(1 * unit, h - 3 * unit); lineTo(1 * unit, h - 4 * unit); lineTo(1 * unit, 3 * unit ); lineTo(2 * unit, 3 * unit ); lineTo(2 * unit, 2 * unit ); lineTo(3 * unit, 2 * unit ); lineTo(3 * unit, 1 * unit ); fill(); restore(); } save(); fillStyle = skyblue; fillRect(w / 2 , 2 * unit, 3 * unit, 1 * unit); fillRect(w / 2 + 4 * unit, 2 * unit, 1 * unit, 1 * unit); restore(); save(); fillStyle = gray; beginPath(); moveTo(3 * unit, h - 4 * unit); lineTo(w / 2 , h - 4 * unit); lineTo(w / 2 , h - 2 * unit); lineTo(4 * unit, h - 2 * unit); lineTo(4 * unit, h - 3 * unit); lineTo(3 * unit, h - 3 * unit); fill(); restore(); save(); fillStyle = navyblue; beginPath(); moveTo(w / 2 , h - 4 * unit); lineTo(w - 3 * unit, h - 4 * unit); lineTo(w - 3 * unit, h - 3 * unit); lineTo(w - 4 * unit, h - 3 * unit); lineTo(w - 4 * unit, h - 2 * unit); lineTo(w / 2 , h - 2 * unit); fill(); restore(); } return canvas.toDataURL(); })();