画布使用字母而不是形状?

时间:2014-02-23 23:52:28

标签: javascript html5 canvas

我写了一个例子,对画布不熟悉我需要帮助将基本圆转换成字母。

Fiddle

以下是您将在小提琴中看到的代码。请注意,圆形绘图是画布中心的内容,我试图使用像B这样的字母代替圆形的酷字体,我只是不确定如何实现它。

所以想象一下圆圈是那个位于该位置的字母,仍然是透明的,矩形覆盖图像的颜色为rgba(255,255,255,0.7)

var canvas = document.getElementById('c');

// resize the canvas to fill browser window dynamically
window.addEventListener('resize', resizeCanvas, false);

function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    /**
     * Your drawings need to be inside this function otherwise they will be reset when 
     * you resize the browser window and the canvas goes will be cleared.
     */
    drawStuff();
}
resizeCanvas();

function drawStuff() {

    if (canvas.getContext) {

        var context = canvas.getContext('2d');
        var centerX = canvas.width / 2;
        var centerY = canvas.height / 2;
        var radius = 70;

        // Full rectangle
        context.fillStyle = 'rgba(255,255,255,0.7)';
        context.fillRect(0, 0, window.innerWidth, window.innerHeight);

        // Inner circle
        context.beginPath();
        context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

        // Add a letter instead of a circle?

        // Hmm
        context.fillStyle = 'rgba(0,0,0,1)';
        context.globalCompositeOperation = 'destination-out';
        context.fill();

    }
}

2 个答案:

答案 0 :(得分:1)

为什么不

context.fillStyle = 'rgba(0,0,0,1)';
context.strokeStyle = "#F00";
context.font = "bold 60pt Arial";
context.globalCompositeOperation = 'destination-out';
context.fillText("B", 20, 50);

http://jsfiddle.net/pqD87/

答案 1 :(得分:1)

这里再次以居中

context.fillStyle = 'rgba(0,0,0,1)';
context.globalCompositeOperation = 'destination-out';
context.textAlign = 'center';
context.font="150px Times";
context.fillText("A",centerX,centerY+40); 

http://jsfiddle.net/x4BuF/1/