使用' no-repeat',' repeat-x'时出现奇怪的问题或者'重复-y'使用图像创建图案时。 请考虑以下事项:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.rect(0, 0, canvas.width, canvas.height);
context.translate(50,50);
var pattern = context.createPattern(imageObj, 'no-repeat');
context.fillStyle = pattern;
context.fill();
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/wood-pattern.png';
</script>
</body>
</html>
我在形状中翻译图像模式(在这种情况下,它是一个矩形,但它适用于任何形状)。在Chrome 35.0.1916.114 m上,它会导致“涂抹”错误。图像。有没有办法避免涂抹效果或我做了一些疯狂的错误。
屏幕截图:
Example Screen Shot http://i59.tinypic.com/2mq2792.jpg
答案 0 :(得分:2)
context.translate
适用于在画布上绘制的起点。相反,你想填充矩形的某个部分。
imageObj.onload = function() {
var width = 600;
var height = 400;
var patOffsetX = 50;
var patOffsetY = 50;
context.rect(0, 0, width, height);
var pattern = context.createPattern(imageObj, 'repeat');
context.fillStyle = pattern;
context.fillRect(patOffsetX, patOffsetY, width - patOffsetX, height - patOffsetY);
context.stroke(); //added to help see the rect
};
我还更新了画布的大小,看它是否有效。
<canvas id="myCanvas" width="800" height="400"></canvas>
答案 1 :(得分:0)
您可以使用剪辑
完成任务演示:http://jsfiddle.net/m1erickson/fHKLk/
示例代码:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house16x16.png";
function start(){
// create a pattern
var pattern = context.createPattern(img,'repeat');
// save the unclipped context state
context.save();
// draw the boundary rect
context.beginPath();
context.rect(20,20,200,200);
context.stroke();
// clip future drawing to inside the boundary rect
context.clip();
// draw a 2nd rect with a 50px offset from the boundary rect
// and using your image pattern
context.fillStyle=pattern;
context.fillRect(20+50,20+50,300,300);
// restore the context to its unclipped state
context.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>