【问题标题】:Define attributes of images generated by canvas2image e.g. alt tag定义 canvas2image 生成的图像的属性,例如替代标签
【发布时间】:2015-10-14 18:31:05
【问题描述】:

我正在使用下面的代码来转换html>canvas>image

  image.src = canvas.toDataURL('jpeg',1.0);
       $('.imagediv').html(image);
////This is just a snippet

我的问题是我想定义其他图像属性宽度、高度、alt、类和一个整洁的文件名 image.jpg。如您所见,图像需要在转换时显示在浏览器中。

【问题讨论】:

    标签: java php jquery html


    【解决方案1】:

    您想要做的非常简单(答案在您添加的示例代码中):只需按照与图像源相同的方式定义不同的属性即可:

    • .src:指定图片来源。
    • .width:指定元素的宽度。
    • .height:指定元素的高度。
    • .alt:指定替代文本。
    • .title:指定标题。
    • .className:指定类。
    • .id:指定元素id。
    • 等等...

    或者,如果您愿意,您可以改用setAttribute() 方法:

    image.setAttribute("alt", "I am the alternative text");
    

    这是一个简单的演示,为使用canvas生成的图像设置不同的属性:

    // get the canvas for manipulation
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext('2d');
    
    // draw a square this is just a test
    context.moveTo(5,5);
    context.lineTo(395,5);
    context.lineTo(395,195);
    context.lineTo(5,195);
    context.lineTo(5,5);
    context.fillStyle = "#FF0000";
    context.fillRect(5,5,390,190);
    context.stroke();
    
    // create the image and set the attributes
    var image = new Image();
    image.src = canvas.toDataURL('jpeg', 1.0);
    image.alt = "A simple red rectangle with black border";
    image.title = "Red rectangle with black border";
    image.width = 400;
    image.height = 200;
    image.className = "myClass";
    
    // place the image inside the div
    document.getElementById('imagediv').appendChild( image );
    .myClass {
        box-shadow:2px 2px 8px red;
    }
    <canvas id="myCanvas" width="400" height="200" style="display:none;"></canvas>
    <div id="imagediv"></div>

    唯一会更复杂的是“整洁的文件名”。 toDataURL 方法返回一个包含图像表示的数据 URI(在 base64 中),这不是一个好看的名称。如果你想显示一个好听的名字,你需要保存文件然后指向它。

    如果您想要一个简洁的文件名,因为用户将能够使用链接下载图片,您可以做的是在锚点中设置download 属性并在此处指定名称。

    类似这样的:

    // get the canvas for manipulation
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext('2d');
    
    // draw a square this is just a test
    context.moveTo(5,5);
    context.lineTo(395,5);
    context.lineTo(395,195);
    context.lineTo(5,195);
    context.lineTo(5,5);
    context.fillStyle = "#FF0000";
    context.fillRect(5,5,390,190);
    context.stroke();
    
    // set the image as the href of the anchor
    document.getElementById("myA").href = canvas.toDataURL('jpeg', 1.0);
    <canvas id="myCanvas" width="400" height="200" style="display:none;"></canvas>
    <a href="" id="myA" download="Red rectangle with border.jpg">Download picture</a>

    【讨论】:

    • 感谢@Alvaro 挽救了我的职业生涯。正是我需要的
    猜你喜欢
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2016-10-07
    相关资源
    最近更新 更多