HTML5 Canvas怎样完成纹路填充与描边(Fill And Stroke

日期:2021-02-25 类型:科技新闻 

关键词:在线小程序开发,微信小程序怎么做店铺,小程序logo设计,小程序平台,小程序码生成

演试HTML5 Canvas Fill 与Stroke文本实际效果,根据Canvas怎样完成纹路填充与描边。

1:色调填充与描边
色调填充能够根据fillStyle来完成,描边色调能够根据strokeStyle来完成。简易示例
以下:

拷贝编码
编码以下:

// fill and stroke text
ctx.font = '60pt Calibri';
ctx.lineWidth = 3;
ctx.strokeStyle = 'green';
ctx.strokeText('Hello World!', 20, 100);
ctx.fillStyle = 'red';
ctx.fillText('Hello World!', 20, 100);

2:纹路填充与描边
HTML5 Canvas还适用纹路填充,根据载入1张纹路图象,随后建立画笔方式,建立纹路方式的API为ctx.createPattern(imageTexture,"repeat");第2主要参数适用4个值,各自为”repeat-x”, ”repeat-y”, ”repeat”,”no-repeat”意思是纹路各自沿着X轴,Y轴,XY方位沿反复或不反复。纹路描边与填充的编码以下:

拷贝编码
编码以下:

var woodfill = ctx.createPattern(imageTexture,"repeat");
ctx.strokeStyle = woodfill;
ctx.strokeText('Hello World!', 20, 200);
// fill rectangle
ctx.fillStyle = woodfill;
ctx.fillRect(60, 240, 260, 440);

纹路照片:
 
3:运作实际效果
 
编码:

拷贝编码
编码以下:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="chrome=IE8">
<meta http-equiv="Content-type" content="text/html;charset=UTF⑻">
<title>Canvas Fill And Stroke Text Demo</title>
<link href="default.css" rel="stylesheet" />
<script>
var ctx = null; // global variable 2d context
var imageTexture = null;
window.onload = function() {
var canvas = document.getElementById("text_canvas");
console.log(canvas.parentNode.clientWidth);
canvas.width = canvas.parentNode.clientWidth;
canvas.height = canvas.parentNode.clientHeight;
if (!canvas.getContext) {
console.log("Canvas not supported. Please install a HTML5 compatible browser.");
return;
}
// get 2D context of canvas and draw rectangel
ctx = canvas.getContext("2d");
ctx.fillStyle="black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// fill and stroke text
ctx.font = '60pt Calibri';
ctx.lineWidth = 3;
ctx.strokeStyle = 'green';
ctx.strokeText('Hello World!', 20, 100);
ctx.fillStyle = 'red';
ctx.fillText('Hello World!', 20, 100);
// fill and stroke by pattern
imageTexture = document.createElement('img');
imageTexture.src = "../pattern.png";
imageTexture.onload = loaded();
}
function loaded() {
// delay to image loaded
setTimeout(textureFill, 1000/30);
}
function textureFill() {
// var woodfill = ctx.createPattern(imageTexture, "repeat-x");
// var woodfill = ctx.createPattern(imageTexture, "repeat-y");
// var woodfill = ctx.createPattern(imageTexture, "no-repeat");
var woodfill = ctx.createPattern(imageTexture, "repeat");
ctx.strokeStyle = woodfill;
ctx.strokeText('Hello World!', 20, 200);
// fill rectangle
ctx.fillStyle = woodfill;
ctx.fillRect(60, 240, 260, 440);
}
</script>
</head>
<body>
<h1>HTML5 Canvas Text Demo - By Gloomy Fish</h1>
<pre>Fill And Stroke</pre>
<div id="my_painter">
<canvas id="text_canvas"></canvas>
</div>
</body>
</html>
上一篇:html5 viewport应用方式示例详解 返回下一篇:没有了