ladybird/Base/res/html/misc/canvas-patterns.html

56 lines
2.3 KiB
HTML
Raw Normal View History

<h1>Canvas Patterns</h1>
<em>Canvas pattern: Repeat (heart)</em><br><code>ctx.createPattern(img, "repeat")</code><br>
<canvas id="canvas-0" width="230" height="210"></canvas><br><br>
<em>Canvas pattern: Repeat</em><br><code>ctx.createPattern(img, "repeat")</code><br>
<canvas id="canvas-1" width="400" height="300"></canvas><br><br>
<em>Canvas pattern: Repeat</em><br><code>ctx.createPattern(img, "repeat-x")</code><br>
<canvas id="canvas-2" width="400" height="300"></canvas><br><br>
<em>Canvas pattern: Repeat</em><br><code>ctx.createPattern(img, "repeat-y")</code><br>
<canvas id="canvas-3" width="400" height="300"></canvas><br><br>
<em>Canvas pattern: Repeat</em><br><code>ctx.createPattern(img, "no-repeat")</code><br>
<canvas id="canvas-4" width="400" height="300"></canvas>
<style>
canvas {
border: 1px solid black;
}
</style>
<script>
const img = new Image();
img.src = "car.png";
img.onload = () => {
const heartDemo = (canvasId) => {
const canvas = document.getElementById(canvasId);
const ctx = canvas.getContext("2d");
const pattern = ctx.createPattern(img, "repeat");
const scale = 1.5
const scaleValues = l =>l.map(value => value * scale);
ctx.fillStyle = pattern;
// Heart path taken from: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes
ctx.beginPath();
ctx.moveTo(...scaleValues([75, 40]));
ctx.bezierCurveTo(...scaleValues([75, 37, 70, 25, 50, 25]));
ctx.bezierCurveTo(...scaleValues([20, 25, 20, 62.5, 20, 62.5]));
ctx.bezierCurveTo(...scaleValues([20, 80, 40, 102, 75, 120]));
ctx.bezierCurveTo(...scaleValues([110, 102, 130, 80, 130, 62.5]));
ctx.bezierCurveTo(...scaleValues([130, 62.5, 130, 25, 100, 25]));
ctx.bezierCurveTo(...scaleValues([85, 25, 75, 37, 75, 40]));
ctx.fill();
}
const makePatternDemo = (canvasId, repeat) => {
const canvas = document.getElementById(canvasId);
const ctx = canvas.getContext("2d");
const pattern = ctx.createPattern(img, repeat);
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
heartDemo("canvas-0")
makePatternDemo("canvas-1", "repeat");
makePatternDemo("canvas-2", "repeat-x");
makePatternDemo("canvas-3", "repeat-y");
makePatternDemo("canvas-4", "no-repeat");
};
</script>