有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java定义由canvas2image生成的图像的属性,例如alt标记

我使用以下代码转换html>;帆布>;形象

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

我的问题是,我想定义其他图像属性width、height、alt、class和整洁的文件名image。jpg。正如您所见,转换时需要在浏览器中显示图像


共 (1) 个答案

  1. # 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中),这不是一个好看的名称。如果你想显示一个好名字,你需要保存文件,然后指向它

    如果您想要一个整洁的文件名,因为用户可以使用链接下载图片,那么您可以在锚中设置^{}属性,并在那里指定名称

    比如:

    // 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>