简体   繁体   English

<canvas>字母形状的clearRect()

[英]<canvas> clearRect() in a letter shape

I've recently started learning web techniques, so I'm still a newbie regarding pretty much everything. 我最近开始学习网络技术,因此,我几乎在所有方面都是新手。 I've stumbled upon this portfolio site, link , which I'm trying to "recreate" as part of my learning process/practice. 我偶然发现了这个投资组合网站link ,这是我尝试“重新创建”的学习过程/练习的一部分。

Here I'm interested in the background of the page, and how to make that transparent letter on canvas. 在这里,我对页面的背景以及如何在画布上制作透明字母感兴趣。 In my current work, I have a html background image set, fillRect() on a full screen with opacity of 0.9 , and now I don't know how to make use of clearRect(). 在我目前的工作中,我在全屏上有一个html背景图像集fillRect(),其不透明度为0.9,而现在我不知道如何利用clearRect()。

The question is: Am I on the right track, and is there any way that I'm not aware of, in which I can use clearRect() to clear pixels on canvas in a letter shape? 问题是:我走在正确的轨道上吗?有什么我不知道的方法可以使用clearRect()清除字母形状的画布上的像素吗? Like, without manually defining a path for clearRect(), but where I would only input a letter and clear pixels in its shape. 就像,无需手动为clearRect()定义路径,但是我只输入一个字母并清除其形状的像素。 Sorry if I posted my current code below the wrong way, it's my first time posting here. 抱歉,如果我以错误的方式发布了当前代码,这是我第一次在此处发布。

var canvas = document.getElementById('layout');
if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
}
$(document).ready(function() {
    window.addEventListener('resize', setCanvasSize); //false
    window.addEventListener('resize', draw); //false
    //set canvas size----------------------------------------
    setCanvasSize();

    function setCanvasSize() {
        canvas.width = $(window).width();
        canvas.height = $(window).height();
    }
    //draw---------------------------------------------------
    draw();

    function draw() {
        var x = canvas.width;
        var y = canvas.height;
        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, x, y);
        ctx.clearRect(50, 30, 110, 35);
    }
});

You can achieve effects such as this using globalCompositeOperation . 您可以使用globalCompositeOperation实现这种效果。

Here's an example where some text is used as shape to erase drawn pixels: 这是一个示例,其中某些文本用作形状来擦除绘制的像素:

var canvas = document.createElement("canvas");
canvas.width = 300;
canvas.height = 200;
var ctx = canvas.getContext("2d");

document.body.appendChild(canvas);

ctx.fillStyle = "rgba(255, 255, 255, 0.8";
ctx.fillRect(0, 0, canvas.width, canvas.height);

ctx.globalCompositeOperation = "destination-out";
ctx.font = "70pt Arial";
ctx.fillText("Text", 50, 130);

Here's the JSFiddle: http://jsfiddle.net/eSpUv/ 这是JSFiddle: http//jsfiddle.net/eSpUv/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM